import axios from 'axios'
import { Message } from 'element-ui'
import { getToken, removeToken } from '@/utils/auth'
import domain from '@/utils/domain'

// create an axios instance
const service = axios.create({
  baseURL: domain.api, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 60000, // request timeout
})

// request interceptor
service.interceptors.request.use(
  (config) => {
    const token = getToken() || null
    if (token) {
      config.headers['Request-Info'] = token
    } else {
      config.headers['Request-Info'] = '*'
    }
    config.headers['Request-Terminal'] = 'webpage'
    config.headers['X-Requested-With'] = 'XMLHttpRequest'
    if (config.blob) {
      config.responseType = 'blob'
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    } else {
      if (config.data instanceof FormData) {
        config.headers['Content-Type'] = 'multipart/form-data'
      } else {
        config.headers['Content-Type'] = 'application/json;charset=UTF-8'
      }
    }
    return config
  },
  (error) => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  (response) => {
    const cts = ['application/vnd.ms-excel']
    for (let i = 0; i < cts.length; i++) {
      if (response.headers['content-type'].indexOf(cts[i]) !== -1)
        return response
    }
    return response.data
  },
  (error) => {
    console.log(error) // for debug
    // Message({
    //   message: error.message,
    //   type: 'error',
    //   duration: 60 * 1000
    // })
    return Promise.reject(error)
  }
)

// export default service

const request = (req) => {
  const type = req.type || 'get'
  const data = req.data || {}
  const blob = req.blob || false
  const url = req.url
  if (!url) return
  return new Promise(async (resolve, reject) => {
    let res
    if (type === 'get') {
      res = await service[type](url, { blob: blob }).catch((error) => {
        reject(error)
      })
    } else {
      res = await service[type](url, data, { blob: blob }).catch((error) => {
        reject(error)
      })
    }
    if (res) {
      if (blob) {
        resolve(res)
      } else {
        if (res || res.code) {
          if (res.code + '' === '200') {
            resolve(res.data)
          } else if (res.code + '' === '201') {
            reject(res)
          } else if (res.code + '' === '205') {
            removeToken()
            window.location.reload()
          } else if (res.code + '' === '301') {
            reject(res)
          } else if (res.code + '' === '404') {
            reject(res)
          } else if (res.code + '' === '305') {
            reject(res)
          }
        } else {
          reject(res)
        }
      }
    } else {
      res = {}
      reject(res)
    }
  })
}

export function post(req) {
  req.type = 'post'
  return request(req)
}

export function get(req) {
  const data = req.data || {}
  let url = req.url
  const param = []
  for (const v in data) {
    param.push(v + '=' + data[v])
  }
  if (param.length > 0) url = url + '?' + param.join('&')
  req.url = url
  req.type = 'get'
  return request(req)
}

export function upload(req) {
  return post(req)
}

export function blob(req) {
  req.blob = true
  return get(req)
}

export function download(req) {
  return domain.api + req.url
}
